<template>
    <div ref="chart"></div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { get_LibraryNumber } from '../../../../api/api';

const props = defineProps({
    selectedStudentId: {
        type: Number,
        required: false,
        default: 1,
    },
});

// 监听 selectedStudentId 的变化
watch(() => props.selectedStudentId, (newValue) => {
    if (newValue) {
        fetchData(newValue);
    }
});

// 获取 token
const getToken = () => {
    return localStorage.getItem('pz_token');
};

// 请求数据并更新图表
const fetchData = async (StudentID) => {
    try {
        const token = getToken();

        if (!token) {
            console.error('未找到 Token');
            return;
        }

        if (!StudentID) {
            console.error('无效的 StudentID:', StudentID);
            return;
        }

        const headers = {
            'Authorization': `JWT ${token}`,
        };

        const response = await get_LibraryNumber(StudentID, headers);

        const LibraryNumber = response.data.data.data;

        // console.log('LibraryNumber:', LibraryNumber);

        if (!LibraryNumber || LibraryNumber.length === 0) {
            console.error('数据为空');
            return;
        }

        const year_month = LibraryNumber.map(item => item.year_month);
        const borrow_count = LibraryNumber.map(item => item.borrow_count);

        option.xAxis[0].data = year_month;
        option.series[0].data = borrow_count;

        const myChart = echarts.init(chart.value);
        myChart.setOption(option);
    } catch (error) {
        console.error('获取数据失败:', error);
    }
};

const chart = ref();
// let xLabel = ['大一上', '大一下', '大二上', '大二下', '大三上', '大三下'];
// let goToSchool = [0, 0, 0, 0, 0, 0];
// let goOutSchool = [0, 0, 0, 0, 0, 0];

const option = reactive({
    backgroundColor: 'rgba(0,0,0,0)',
    tooltip: {
        trigger: 'axis',
        backgroundColor: 'transparent',
        axisPointer: {
            lineStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(126,199,255,0)'
                    }, {
                        offset: 0.5,
                        color: 'rgba(126,199,255,1)'
                    }, {
                        offset: 1,
                        color: 'rgba(126,199,255,0)'
                    }],
                    global: false
                }
            },
        },
        formatter(res) {
            if (!res || res.length === 0) {
                return '';
            }
            return '<p style="margin:-10px;padding:10px;width:200px;height:80px;color:white; no-repeat;background-size:100% 100%">' +
                res[0].axisValue + "<br />" +
                (res[0].seriesName || '') + "：" + (res[0].value || '') + "<br />" +
                (res[1] ? (res[1].seriesName || '') + "：" + (res[1].value || '') : '') +
                '</p>';
        }
    },
    legend: {
        align: "left",
        right: '0%',
        top: '0%',
        type: 'plain',
        textStyle: {
            color: '#7ec7ff',
            fontSize: 11
        },
        itemGap: 50,
        itemWidth: 100,
        itemHeight: 10,
        icon: 'path://M0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z',
        data: [
            { name: '图书馆进入次数' },
            { name: '专业平均图书馆进入次数' }
        ]
    },
    grid: {
        top: '10%',
        left: '8%',
        right: '4%',
        bottom: '17%',
    },
    xAxis: [{
        type: 'category',
        boundaryGap: false,
        axisLine: {
            show: true,
            lineStyle: {
                color: '#233653'
            },
        },
        axisLabel: {
            color: '#7ec7ff',
            padding: 1,
            fontSize: 11,
            formatter: function (data) {
                return data;
            }
        },
        splitLine: {
            show: true,
            lineStyle: {
                color: '#192a44'
            },
        },
        axisTick: {
            show: false,
        },
        data: ['大一上', '大一下', '大二上', '大二下', '大三上', '大三下'],
    }],
    yAxis: [{
        name: '',
        nameTextStyle: {
            color: "#7ec7ff",
            fontSize: 16,
            padding: 10
        },
        min: 0,
        splitLine: {
            show: true,
            lineStyle: {
                color: '#192a44'
            },
        },
        axisLine: {
            show: true,
            lineStyle: {
                color: "#233653"
            }
        },
        axisLabel: {
            show: true,
            color: '#7ec7ff',
            padding: 1
        },
        axisTick: {
            show: false,
        },
    }],
    series: [{
        name: '图书馆进入次数',
        type: 'line',
        symbol: 'circle',
        showAllSymbol: true,
        symbolSize: 0,
        smooth: false,
        lineStyle: {
            width: 4,
            color: "rgba(25,163,223,1)",
            borderColor: 'rgba(0,0,0,.4)',
        },
        itemStyle: {
            color: "rgba(25,163,223,1)",
            borderColor: "#646ace",
            borderWidth: 2
        },
        areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: "rgba(25,163,223,.3)"
            },
            {
                offset: 1,
                color: "rgba(25,163,223, 0)"
            }
            ], false),
            shadowColor: 'rgba(25,163,223, 0.5)',
            shadowBlur: 20
        },
        data: [0, 0, 0, 0, 0, 0]
    }, {
        name: '专业平均图书馆进入次数',
        type: 'line',
        symbol: 'circle',
        showAllSymbol: true,
        symbolSize: 0,
        smooth: false,
        lineStyle: {
            width: 4,
            color: "rgba(10,219,250,1)",
            borderColor: 'rgba(0,0,0,.4)',
        },
        itemStyle: {
            color: "rgba(10,219,250,1)",
            borderColor: "#646ace",
            borderWidth: 2
        },
        areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: "rgba(10,219,250,.3)"
            },
            {
                offset: 1,
                color: "rgba(10,219,250, 0)"
            }
            ], false),
            shadowColor: 'rgba(10,219,250, 0.5)',
            shadowBlur: 20
        },
        data: [0, 0, 0, 0, 0, 0]
    }]
});

onMounted(() => {
    const myChart = echarts.init(chart.value);
    myChart.setOption(option);

    const resizeHandler = () => {
        myChart.resize();
    };
    window.addEventListener('resize', resizeHandler);

    // let len = 0;
    // setInterval(() => {
    //     if (len === xLabel.length) {
    //         len = 0;
    //     }
    //     myChart.dispatchAction({
    //         type: 'showTip',
    //         seriesIndex: 0,
    //         dataIndex: len,
    //     });
    //     len++;
    // }, 1000);

    onUnmounted(() => {
        window.removeEventListener('resize', resizeHandler);
    });
});
</script>

<style lang="less" scoped></style>